package com.zt.chatglm.interceptor;

import com.zt.chatglm.session.Configuration;
import com.zt.chatglm.utils.BearerTokenUtils;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 * @author: zt
 * @Description: 接口拦截器-用于填充jwt信息
 * @create: 2024-05-20 23:27
 */

public class ChatGLMHTTPInterceptor implements Interceptor {

    /**
     * 智普Ai，Jwt加密Token
     */
    private final Configuration configuration;

    public ChatGLMHTTPInterceptor(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * https://open.bigmodel.cn/dev/api#http_para
     * 请求头
     * Content-Type：application/json
     * Authorization：支持API Key 和 token 两种鉴权方式
     * 新版机制中平台颁发的 API Key 同时包含 “用户标识 id” 和 “签名密钥 secret”，即格式为 {id}.{secret}
     * @param chain
     * @return
     * @throws IOException
     */
    @Override
    public Response intercept(Chain chain) throws IOException {
        // 1. 获取原始请求
        Request originalRequest = chain.request();

        // 2. 构建处理后的请求
        Request request = originalRequest.newBuilder()
                .url(originalRequest.url())
                .header("Authorization", "Bearer " + BearerTokenUtils.getToken(configuration.getApiKey(), configuration.getApiSecret()))
                .header("Content-Type", Configuration.JSON_CONTENT_TYPE)
                .header("User-Agent", Configuration.DEFAULT_USER_AGENT)
                .method(originalRequest.method(), originalRequest.body())
                .build();

        // 3. 返回处理后的请求
        return chain.proceed(request);
    }
}
